<template>
  <el-card class="clubListMain" style="max-width: 75vw">
    <div>
      <el-input class="searchText" v-model="clubNameSearch" placeholder="输入社团名" />
      <el-button type="primary" @click="handleResearch">查询</el-button>
    </div>
    <div>
      <el-table class="listTable" :data="clubListData" :border=true style="width: 100%" :max-height="'70vh'">
        <el-table-column prop="clubName" label="社团名称" :width="tableWidth[0]" :align="'center'" />
        <el-table-column prop="level" label="社团级别" :width="tableWidth[1]" :align="'center'" />
        <el-table-column prop="number" label="社团人数" :width="tableWidth[2]" :align="'center'" />
        <el-table-column prop="status" label="社团状态" :width="tableWidth[3]" :align="'center'" />
        <el-table-column prop="options" label="操作" :width="tableWidth[4]" :align="'center'">
          <template #default="scope">
            <el-button id="buttonClubShow" @click="handleShowClub(scope.row)">查看详情</el-button>
            <el-button id="" @click="handleShowMembers(scope.row)">查看成员</el-button>
            <el-button type="primary" id="" @click="handleChangeInfo(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footerpager">
          <el-select v-model="pageSize" @change="onOptionChange" placeholder="Select" style="width: 120px">
            <el-option
              v-for="size in pageSizeOptions"
              :key="size.value"
              :label="size.label"
              :value="size.value"
            />
          </el-select>
          <el-pagination class="pagdivision"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :pager-count="7"
          @current-change="handleUpdateList"
          layout="prev, pager, next"
          :total="totalNum" />
          <div class="pageNow">
            当前
            <input class="pageInput" @blur="onChangePage" v-model="setCurrentPage"/>
            页，共
            {{ totalPage }}
            页
          </div>
        </div>
  </el-card>

  <el-dialog v-model="dialogVisible" title="修改社团信息" width="800">
    <el-form  label-width="auto">
      <el-form-item label="头像">
        <div class="avatarChange">
          <el-avatar id="avatarImg" :size="55" :src="clubFormData.backImage" />
          <el-upload class="avatar-uploader" :beforeUpload="beforeImgUpload" :show-file-list="false"
            :accept="'image/jpeg,image/jpg,image/png,.jpg,.png,.jpeg'">
            <el-button id="uploadButton" type="primary">修改头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="社团名称">
        <el-input v-model="clubFormData.clubName" style="width: 260px"/>
      </el-form-item>
      <el-form-item label="社团级别">
        <el-radio-group v-model="clubFormData.clubLevel">
          <el-radio :value="1">院级</el-radio>
          <el-radio :value="0">校级</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="社团状态">
        <el-radio-group v-model="clubFormData.clubState">
          <el-radio :value="0">正常</el-radio>
          <el-radio :value="1">不可加入</el-radio>
          <el-radio :value="2">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="社团负责人">
        <el-input v-model="adminName" style="width: 240px" placeholder="输入姓名关键词" />
        <el-button @click="lookupAdmin">查询负责人</el-button>
        <el-button @click="clearAdmin">清除已选</el-button>
      </el-form-item>
      <el-form-item label="社团简介">
        <el-input v-model="clubFormData.introduction" type="textarea" maxlength="500" show-word-limit placeholder="请输入社团简介"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认修改</el-button>
        <el-button type="danger" @click="deleteClub">永久删除该社团</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogTwice"
    title="提示"
    width="500"
  >
    <span>你确定要永久删除该社团吗？<div>（该操作不可恢复）</div></span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTwice = false">取消</el-button>
        <el-button type="primary" @click="deleteClubForever">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-drawer v-model="drawer" title="查询结果如下" direction='ltr' >
    <span>
      <el-select @change="newAdmin"
      v-model="adminSelect"
      placeholder="--请选择--"
      size="large"
      style="width: 300px"
    >
      <el-option
       v-for="item in options" 
       :key="item.id"
       :label="item.id+`&nbsp&nbsp`+item.userName"
       :value="item.id"
      />
    </el-select>
    </span>
  </el-drawer>
</template>

<script setup>
import { onMounted, reactive, ref,watch,onUnmounted } from 'vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import router from '@/router';
import userStore from '@/stores/store';
import debounce from '@/utils/debounce';

const clubListData = ref([]);
const tableWidth=ref([]);
const tableWidthRatio=ref([0.29,0.11,0.11,0.11,0.38]);
const dialogVisible = ref(false);
const dialogTwice= ref(false);
const clubFormData = reactive({});
const temp = reactive({});
const imgData = ref(null);
const clubId = ref();
const pageSize = ref(10);
const totalPage = ref(1); //总页数
const pageSizeOptions = ref([
  { value: 5, label: '5条/页' },
  { value: 10, label: '10条/页' },
  { value: 15, label: '15条/页' },
  { value: 20, label: '20条/页' },
]);
const totalNum = ref(0);
const currentPage = ref(1);
const setCurrentPage = ref();
const options = ref([]);
const drawer=ref(false);
const adminSelect = ref(null);
const adminName = ref('');
const clubNameSearch = ref('');
var debounceSetColumnSize = null;

onMounted(async  () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
  handleUpdateList();
});
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
}

const onOptionChange = async () => {
  setCurrentPage.value = 1;
  currentPage.value = 1;
  await handleUpdateList();
}
watch(pageSize, async (newQuestion, oldQuestion) =>{
  await handleUpdateList();
})
const handleUpdateList = async() => { //需要加搜索
  const reqData = reactive({
    page:currentPage.value,
    pageSize:pageSize.value,
  })
  if(clubNameSearch.value != ''){
    reqData.clubName = clubNameSearch.value;
  }
  const resultList =await api.getClubList(reqData);
  switch(resultList[0])
    {
      case 0:
        const data = resultList[1].data;
        if(data.code == 1){
          totalNum.value = data.data.total;
          clubListData.value = [];
          const tableData = data.data.rows;
          for(let i=0;i<tableData.length;i++){
            const temp = reactive({});
            if(tableData[i].clubLevel == 0){
              temp.level = "校级";
            }
            else{
              temp.level = "院级";
            }
            if(tableData[i].clubState == 0){
              temp.disabled = false;

              temp.status = "可加入"
            }
            else if(tableData[i].clubState == 1){
              temp.disabled = true;
              temp.status = "不可加入";
            }
            else{
              temp.disabled = true;
              temp.status = "停用";
            }
            Object.assign(temp,{
              clubName:tableData[i].clubName,
              number:tableData[i].number,
              clubId:tableData[i].clubId,
            });
            clubListData.value[i] = temp;
          }
         totalPage.value = Math.ceil(data.data.total/pageSize.value);
        }
        else{
          showMessageTip("加载失败！",'error');
          return;
        }
        break;
      case 1:
        showMessageTip("服务器响应错误，代码:"+resultList[1].status+"，请再次尝试",'error')
        break;
      case 2:
        showMessageTip("连接服务器失败,请检查网络",'error')
        break;
      case 3:
        showMessageTip("请求发送失败",'error')
        break;
    }
    setCurrentPage.value = currentPage.value;
}
const handleChangeInfo = async (rowData) => {
  await getClubInfo(rowData.clubId);
  clubId.value = rowData.clubId;
  dialogVisible.value = true;
}

const getClubInfo = async (clubId) => {
  const reqData = await api.getBasicClubInfo({ clubId:clubId });
  if(reqData[0] == 0){
    const data = reqData[1].data;
    if(data.code == 1){
      clearData(clubFormData);
      clearData(temp);
      Object.assign(clubFormData,{...data.data});
      Object.assign(temp,{...clubFormData});
    }
    else{
      showMessageTip('数据获取失败','error');
    }
  }
  else{
    showMessageTip('网络请求失败','error');
    return;
  }
}

const onSubmit = async () => {
  const formData = new FormData();
  let flag = false;
  if(imgData.value != null){
    formData.append('image',imgData.value);
    flag = true;
  }
  if(clubFormData.clubName == ''){
    showMessageTip('社团名不能为空！','warning');
    return;
  }
  else if(clubFormData.clubName != temp.clubName){
    formData.append('clubName',clubFormData.clubName);
    flag = true;
  }
  if(clubFormData.introduction != temp.introduction){
    formData.append('introduction',clubFormData.introduction);
    flag = true;
  }
  if(clubFormData.clubState != temp.clubState){
    formData.append('clubState',clubFormData.clubState);
    flag = true;
  }
  if(clubFormData.clubLevel != temp.clubLevel){
    formData.append('clubLevel',clubFormData.clubLevel);
    flag = true;
  }
  if(adminSelect.value != null){
    formData.append('managerId',adminSelect.value)
    flag = true;
  }
  if(!flag){
    showMessageTip('无修改内容','warning');
    return;
  }
  formData.append('clubId',clubId.value);
  const result = await api.updateClubInfo(formData);
  if(result[0] == 0){
    const data = result[1].data;
    if(data.code == 1){
      clearData(temp);
      clearData(clubFormData);
      imgData.value = null;
      showMessageTip('提交成功','success');
      dialogVisible.value = false;
      return;
    }
    else{
      showMessageTip('提交失败','error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败！','error');
    return;
  }
}
const deleteClub=()=>{
    dialogTwice.value=true;
}
const deleteClubForever=async()=>{//永久删除当前社团
    //发送申请
    const id = ref({id: clubId.value });
    const result = await api.deleteClub(id.value)
    if(result[0]==0){
      const data = result[1].data;
      if(data.msg=='success'){
        dialogVisible.value = false;
      showMessageTip('已永久删除该社团','success');
    dialogTwice.value=false;
      }
      else{
        showMessageTip('操作失败，请重试','success');
      }      
    }
    else{
      showMessageTip('网络请求失败','error')
    }   
} 
const clearData = (data) => {
  data.clubName = '';
  data.introduction = '';
  data.clubState = -1;
  data.backImage = '';
  data.clubLevel = -1;
  data.reason = '';
}

const beforeImgUpload = async (file) => {
    if (!file.type.startsWith('image/')) {
        showMessageTip('不支持的文件格式', 'warning');
        return false;
    }
    else if (!(file.size / 1024 / 1024 < 2)) {
        showMessageTip('文件不能大于2M', 'warning')
        return false;
    }
    else {
        imgData.value = file;
        if (imgData.value != null) {
            clubFormData.backImage = await imgToUrl(imgData.value);
            showMessageTip('图片加载成功！', 'success');
        }
        return false;
    }
}
const imgToUrl = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
            resolve(event.target.result); // 返回Base64URL
        };
        reader.onerror = (error) => {
            reject(new Error('文件读取错误' + error));
        };
        reader.readAsDataURL(file);
    });
}

const lookupAdmin = async () => {
  const searchResult = await api.getSbIdName({ userName: adminName.value });
  if (searchResult[0] == 0) {
    const data = searchResult[1].data;
    if (data.code == 1) {
      drawer.value = true;
      const researchList = data.data;
      options.value = [];
      options.value = researchList;
      showMessageTip('查询成功', 'success');
      return;
    }
    else{
      showMessageTip('数据获取失败', 'error');
    }
  }
  else {
    showMessageTip('网络请求失败', 'error');
    return;
  }
};
const clearAdmin = () => {
  adminSelect.value = null;
  adminName.value = '';
}
const newAdmin = () => {
  clubListData.admin=adminSelect.value;
  const temp =ref();
  temp.value = options.value.find(item =>item["id"]===adminSelect.value );
  adminName.value=temp.value.userName;
}
const handleResearch= async ()=>{
  setCurrentPage.value = 1;
  currentPage.value = 1;
  await handleUpdateList();
}

const handleShowClub = (rowData) => {
  userStore().setClubID(rowData.clubId);
  router.push('/managesys/clubview');
}
const handleShowMembers = (rowData) => {
  userStore().setClubID(rowData.clubId);
  router.push('memberinfo');
}
const onChangePage = async () => {
  if(Number(setCurrentPage.value) > totalPage.value){
    setCurrentPage.value = totalPage.value;
    currentPage.value = totalPage.value;
  }
  else if(setCurrentPage.value <= 0){
    setCurrentPage.value = 1;
    currentPage.value = 1;
  }
  else{
    currentPage.value = Number(setCurrentPage.value);
  }
  await handleUpdateList();
}
</script>

<style scoped>
.footerpager{
  margin-top: 20px;
  padding-left: 5px;
  display: flex;
}
.listTable{
  margin-top: 12px;
}
:deep(.listTable .el-table__header-wrapper th){
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}
.avatarChange{
  display: flex;
  align-items: center;
}
.pagdivisiong {
  left: 40%;
  position: relative;
}
.pageNow{
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14.5px;
}
.pageInput{
  margin-left: 5px;
  margin-right: 5px;
  width: 25px;
  text-align: center;
}
#uploadButton{
  margin-left: 20px;
}
.searchText{
  margin-left: 5px;
  width: 240px;
  margin-right: 20px;
}
</style>